package com.mt.component.validate;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mt.utils.NumberUtils;

/**
 * 
 * 类名称：ValidateCode <br>
 * 类描述： <br>
 * 创建人： 马腾 <br>
 * 创建时间：Nov 28, 2012 10:39:21 PM <br>
 * 修改人： 马腾 <br>
 * 修改时间：Nov 28, 2012 10:39:21 PM <br>
 */
public class ValidateCode extends HttpServlet {

	private static final long serialVersionUID = -974640047984152028L;
	
	private Font font = new Font("宋体", Font.PLAIN, 22);
	private int width = 105;
	private int height = 27;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.reset();
		// 响应类型,即MIME类型
		response.setContentType("image/png");
		// 不缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = (Graphics2D) image.getGraphics();
		g.setColor(getRandColor(200, 250));

		g.fillRect(0, 0, width, height);
		g.setFont(font);
		g.setColor(getRandColor(160, 230));

		int a = new Random().nextInt(10);
		int b = new Random().nextInt(10);
		String str = NumberUtils.getChineseNum(a) + " + " + NumberUtils.getChineseNum(b) + " = ";
		g.drawString(str , 5, 21);
		
		request.getSession().setAttribute("validate", a + b);
		
		// 关闭画笔
		g.dispose();

		// 写出
//		ImageIO.write(image, "JPEG", response.getOutputStream());
		ImageIO.write(image, "PNG", response.getOutputStream());
	}
	
	/**
     * 生成随机颜色
     * @param fc
     * @param bc
     * @return
     */
	public Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}
}
